package com.hxd.otc.module.my.activity;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.verificationsdk.ui.VerifyType;
import com.hxd.otc.R;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.my.bean.ImageCodeBean;
import com.hxd.otc.module.my.contract.BindEmailContract;
import com.hxd.otc.module.my.presenter.BindEmailPresenter;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.VerifyTypeUtils;
import com.hxd.otc.widget.EditInfoInputView;
import com.hxd.otc.widget.TitleBar;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

/**
 * eg：2018/10/18 暂只支持绑定，不支持修改绑定
 */
public class BindEmailActivity extends BaseActivity<BindEmailPresenter> implements BindEmailContract.IView {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.tv_old_email_label)
    TextView mTvOldEmailLabel;
    @BindView(R.id.et_old_email)
    EditText mEtOldEmail;
    @BindView(R.id.editInfoInputView_ver_code)
    EditInfoInputView mEditInfoInputViewVerCode;
    @BindView(R.id.btn_verification_code)
    TextView mBtnVerificationCode;
    @BindView(R.id.tv_new_email_label)
    TextView mTvNewEmailLabel;
    @BindView(R.id.et_new_email)
    EditText mEtNewEmail;
    @BindView(R.id.editInfoInputView_new_ver_code)
    EditInfoInputView mEditInfoInputViewNewVerCode;
    @BindView(R.id.btn_new_verification_code)
    TextView mBtnNewVerificationCode;
    @BindView(R.id.tv_confirm)
    TextView mTvConfirm;
    private Disposable mEmailDisposable;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bind_email;
    }

    @Override
    protected BindEmailPresenter createPresenter() {
        return new BindEmailPresenter(this);
    }

    @Override
    protected void initView() {
        boolean isBoundEmail = UserHelper.isBoundEmail();

        if (isBoundEmail) {
            mEtOldEmail.setEnabled(false);
            mEtOldEmail.setText(UserHelper.getEmail());
        }

        mTvOldEmailLabel.setText(isBoundEmail ? R.string.old_email : R.string.email_label);
        mTitleBar.setTitleText(getString(isBoundEmail ? R.string.modify_bind_email : R.string.bind_email));
        mTvNewEmailLabel.setVisibility(isBoundEmail ? View.VISIBLE : View.GONE);
        mEtNewEmail.setVisibility(isBoundEmail ? View.VISIBLE : View.GONE);
        mBtnNewVerificationCode.setVisibility(isBoundEmail ? View.VISIBLE : View.GONE);
        mEditInfoInputViewNewVerCode.setVisibility(isBoundEmail ? View.VISIBLE : View.GONE);
    }


    @OnClick({R.id.btn_verification_code, R.id.btn_new_verification_code, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_verification_code:
                onSendEmailCode();
                break;
            case R.id.btn_new_verification_code:
                break;
            case R.id.tv_confirm:
                onConfirm();
                break;
        }
    }

    VerifyTypeUtils verifyTypeUtils;

    private void onSendEmailCode() {
        final String email = mEtOldEmail.getText().toString().trim();
        if (!DataUtils.isEmail(email)) {
            return;
        }
        mBtnVerificationCode.setEnabled(false);
        verifyTypeUtils = new VerifyTypeUtils();
        verifyTypeUtils.callSDKDoVerification(VerifyType.NOCAPTCHA, null, this, new VerifyTypeUtils.VerifyTypeCallBack() {
            @Override
            public void onSucced(String sessionID) {
                mPresenter.sendEmailCode(email, sessionID);
            }
        });
        mBtnVerificationCode.setEnabled(true);
    }

    private void onConfirm() {
        String email = mEtOldEmail.getText().toString().trim();
        if (!DataUtils.isEmail(email)) {
            return;
        }
        String verCode = mEditInfoInputViewVerCode.getText().toString().trim();
        if (TextUtils.isEmpty(verCode)) {
            showToast(getString(R.string.email_code_not_null));
            return;
        }

        mPresenter.bindEmail(email, verCode);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initEvent() {
    }

    @Override
    public void getEmailCodeSuccess(ImageCodeBean imageCodeBean) {
        startCountdown();
    }

    @Override
    public void bindEmailSuccess(String email) {
        UserHelper.updateEmail(email);
        showToast(getString(R.string.bind_email_success));
        finish();
    }

    private void startCountdown() {
        ViewGroup.LayoutParams layoutParams = mBtnVerificationCode.getLayoutParams();
        layoutParams.width = mBtnVerificationCode.getWidth();
        mBtnVerificationCode.setLayoutParams(layoutParams);
        mBtnVerificationCode.setEnabled(false);
        if (mEmailDisposable != null && !mEmailDisposable.isDisposed()) {
            mEmailDisposable.dispose();
            mEmailDisposable = null;
        }
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mEmailDisposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) throws Exception {
                        mBtnVerificationCode.setText(String.format("%ds", 60 - aLong));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //倒计时完毕置为可点击状态
                        mBtnVerificationCode.setEnabled(true);
                        mBtnVerificationCode.setText(R.string.send_message_code);
                    }
                })
                .subscribe();
    }

    @Override
    protected void onDestroy() {
        if (mEmailDisposable != null && !mEmailDisposable.isDisposed()) {
            mEmailDisposable.dispose();
            mEmailDisposable = null;
        }
        super.onDestroy();
    }
}
